package com.yj.auto.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;

import com.jfinal.log.Log;
import com.yj.auto.helper.LogHelper;

public abstract class AutoJob implements Job {
	private static final Log logger = Log.getLog(AutoJob.class);
	private static final List<String> queue = new ArrayList<String>();

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// 任务ID
		JobKey key = context.getJobDetail().getKey();
		String code = key.toString();
		if (queue.contains(code)) {
			logger.info("定时任务[" + code + "]尚未执行完成。");
			return;
		}
		Integer jobId = Integer.parseInt(key.getName());
		Date stime = new Date();// 开始时间

		boolean success = true;
		String msg = null;
		try {
			run(context);// 执行具体任务
		} catch (Exception e) {
			logger.error("定时任务[" + jobId + "]，执行异常。", e);
			success = false;
			msg = e.getMessage();
		} finally {
			queue.remove(code);
		}

		Date etime = new Date();// 结束时间
		LogHelper.addScheduleLog(jobId, stime, etime, success, msg);
	}

	/**
	 * 定时任务
	 * 
	 * @param context
	 */
	public abstract void run(JobExecutionContext context);
}
